var wueditor;
$(function () {
    f();
    uploadImg();
});
var postId;

//获取地址栏参数
function GetQueryString() {
    var loc = location.href;
    var pp = loc.split("?postId=")[1];
    postId = pp.split("&")[0];
    if (postId != null) return postId;
    return null;

}

//获取地址栏参数，发送ajax
function f() {
    var poId = GetQueryString();
    $.ajax({
        type: "GET",
        url: "/front/blog/" + poId,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
            if (data.code === "200") {
                $("#po_title").text(data.data.postTitle);//标题
                $("#post_data").text(fmt(data.data.postDate));//上传日期
                $("#author").text(data.data.user.userName);
                var converter = new showdown.Converter();
                var showmarkdowntohtml = converter.makeHtml(data.data.postContent);
                $("#content").html(data.data.postContent);//内容
                $("#category_desc").text(data.data.category.cateName);//类型描述
                //加载标签
                loadTags(data.data.postId);
                //加载评论
                loadComment();
            } else {
                //layer.msg(data.msg, {time: 1 * 1000});
            }
        }
    });
}

function loadTags(postTags) {
    $.ajax({
        type: "GET",
        url: "/tag/api/selecttags?postId=" + postTags,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            var list = data.tagList;
            $("#tags").empty();
            var tagHtml = '';
            for (var i = 0; i < list.length; i++) {
                tagHtml =
                    '<a href="/web/tags?tagId=' + list[i].tagId + '" class="tag">' + list[i].tagName + '</a>';
                $("#tags").append(tagHtml)
            }



        }
    });
}

var parentData;
var ap = '';

function loadComment() {
    var poId = GetQueryString();
    $.ajax({
        type: "GET",
        url: "/detail/cms/commentsCount?postId=" + poId,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            layui.use('laypage', function () {
                var laypage = layui.laypage;

                //执行一个laypage实例
                laypage.render({
                    elem: 'loadPage', //注意，这里的 test1 是 ID，不用加 # 号
                    count: data, //数据总数，从服务端得到
                    curr: 1,
                    limit: 5,//每页条数
                    jump: function (obj, first) {
                        //obj包含了当前分页的所有参数，比如：
                        //得到当前页，以便向服务端请求对应页的数据。console.log(obj.curr);
                        //得到每页显示的条数 console.log(obj.limit);
                        $.ajax({
                            type: "GET",
                            url: "/front/comment/" + poId + '?page=' + obj.curr + '&limit=' + obj.limit,
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function (data) {
                                $("#showComment").empty();
                                $("#commentsNum").html('<img src="/static/images/comment-icon-gray.png" alt="">' + data.total);//总回复数
                                if (data.total > 0) {
                                    var Commenthtml = '';
                                    for (var i = 0; i < data.records.length; i++) {
                                        //正常评论 没有回复别人，没有被回复
                                        if (data.records[i].commentChild === "") {
                                            Commenthtml = '<div class="media comment">' +
                                                '<div class="media-left">' +
                                                '<a href="javascript:;"><img src="' + data.records[i].commentAuthorAvatarMd5 + '" alt="" class="img-circle" style="width: 50px;height: 50px;"></a>' +
                                                '</div>' +
                                                '<div class="media-body">' +
                                                '<h4><label style="font-size: 20px">' + data.records[i].commentAuthor + '</label></h4>' +
                                                '<h5><a href="javascript:;" class="date">' + fmt(data.records[i].commentDate) + '</a> | <a href="javascript:;" onclick="showForm(' + data.records[i].commentId + ')"  class="reply-link ">reply</a>' +
                                                ' </h5>' +
                                                ' <p>' + data.records[i].commentContent + '</p>' +
                                                '</div>' +
                                                '<hr></hr>' +
                                                '</div>';
                                            $("#showComment").append(Commenthtml);
                                            Commenthtml = '';
                                        }
                                        //筛选被回复的楼层 加载回复
                                        else if (data.records[i].commentChild !== "") {
                                            var replyHtml = '';
                                            showParents(data.records[i].commentChild);
                                            if (parentData.data != null) {
                                                for (var j = 0; j < parentData.data.length; j++) {
                                                    replyHtml = '<div class="media comment reply">' +
                                                        '<div class="media-left">' +
                                                        // parentData.records[j].commentAuthorAvatarMd5
                                                        '<a href="javascript:;"><img src=" ' + parentData.data[j].commentAuthorAvatarMd5 + '" alt="" class="img-circle" style="width: 50px;height: 50px;"></a>' +
                                                        '</div>' +
                                                        '<div class="media-body">' +
                                                        ' <h4><a href="javascript:;">' + parentData.data[j].commentAuthor + '</a></h4>' +
                                                        '<h5><a href="javascript:;" class="date">' + fmt(parentData.data[j].commentDate) + '</a> | <a href="javascript:;" onclick="showForm(' + parentData.data[j].commentId + ')" class="reply-link">reply</a></h5>' +
                                                        '<p>' + parentData.data[j].commentContent + '</p>' +
                                                        '</div>' +
                                                        ' </div>';
                                                    ap += replyHtml
                                                }
                                            }
                                            Commenthtml =
                                                //回复者 start <i  style="float: right;cursor: pointer;font-style:normal" onclick="showParents(' + data.records[i].commentParent + ')"> >>>>ReplyTo:      ' + data.records[i].commentAuthor + '</i>
                                                '<div class="media comment " >' +
                                                '<div class="media-left">' +
                                                '<a href="javascript:;"><img src="' + data.records[i].commentAuthorAvatarMd5 + '" alt="" class="img-circle" style="width: 50px;height: 50px;"></a>' +
                                                '</div>' +
                                                '<div class="media-body">' +
                                                '<div name="parent_content"></div>' +
                                                '<h4><label style="font-size: 15px">' + data.records[i].commentAuthor + '</label></h4>' +
                                                '<h5><a href="javascript:;" class="date">' + fmt(data.records[i].commentDate) + '</a> | <a href="javascript:;" onclick="showForm(' + data.records[i].commentId + ')" class="reply-link">reply</a>' +
                                                ' </h5>' +
                                                ' <p>' + data.records[i].commentContent + '</p>' +
                                                ap +
                                                '</div>' +
                                                '<hr></hr>' +
                                                '</div>';
                                            $("#showComment").append(Commenthtml);
                                            Commenthtml = '';
                                            ap = '';
                                        }
                                    }

                                } else {
                                    console.log(11111111)
                                }
                            }
                        });

                        //首次不执行
                        if (!first) {
                            //do something
                        }
                    }
                });
            });


        }
    });
}

//显示楼层评论
function showParents(parentId) {
    $.ajax({
        type: "GET",
        cache: false,
        async: false,
        url: "/detail/cms/" + parentId,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            parentData = data;
        }
    });
}

$('#comment_form').on('click', function () {
    showForm();
});
$('#cms_sub').on('click', function () {
    cmsSend();
});

//显示评论操作
function showForm(id) {
    if (id != null || id !== "") {
        $("#reply_po").val(id)
    }
    $("#comment_post").show();
    editoractive();
}

//上传头像图片
function uploadImg() {
    layui.use('upload', function () {
        var upload = layui.upload;
        //执行实例
        var uploadInst = upload.render({
            elem: '#imgupload',//绑定元素
            url: 'http://crawler_upload.6ack.com/upload',  //上传接口
            done: function (res) {
                var getbegin = res.message.lastIndexOf('/');
                var getend = res.message.lastIndexOf('.');
                var imgid = res.message.substring(getbegin + 1, getend);
                $("#show_newsimg_update").empty();
                $("#pic").attr("src", res.message);
                $("#demoText").text(res.message);
                // $("#show_newsimg").attr("src",res.message);
                console.log(res)
            }
            , error: function (res) {
                //请求异常回调
                console.log(res)
            }
        });
    });
}

function cmsSend() {
    var reply_po = $("#reply_po").val(),
        imgspan = $("#demoText").text(),
        name = $("#name").val(),
        htmlContent = wueditor.getHTML(),

        data = {};
    data.commentParent = reply_po;
    data.commentAuthorAvatarMd5 = imgspan;
    data.commentAuthor = name;
    data.commentContent = htmlContent;
    data.postId = GetQueryString();
    console.log(GetQueryString());
    $.ajax({
        type: "POST",
        url: "/detail/cms/send",
        dataType: "json",
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
        }
    });

}

// //layui的富文本 没有emoji 没有灵魂
// function laytextarea() {
//     layui.use('layedit', function () {
//         var layedit = layui.layedit;
//         layedit.set({
//             uploadImage: {
//                 url: 'http://crawler_upload.6ack.com/upload/layedit' //接口url
//                 , type: 'POST' //默认post
//             }
//         });
//         //构建一个默认的编辑器
//         var index = layedit.build('message',{
//             height: 180 //设置编辑器高度
//         });
//         //编辑器外部操作
//         var active = {
//             content: function () {
//                 console.log(layedit.getContent(index)); //获取编辑器内容
//             }
//             , text: function () {
//                 alert(layedit.getText(index)); //获取编辑器纯文本内容
//             }
//             , selection: function () {
//                 alert(layedit.getSelection(index));
//             }
//         };
//     })
// }
//激活editor
function editoractive() {
    // laytextarea();
    wueditor = editormd("content-editormd", {//注意1：这里的就是上面的DIV的id属性值
        placeholder: '欢迎使用',
        width: "100%",
        height: 440,
        watch: false,
        //theme : "dark",
        // previewTheme : "dark",
        // editorTheme : "pastel-on-dark",
        htmlDecode: "style,script,iframe|on*",
        emoji: true,//emoji表情
        syncScrolling: "single",
        path: "/static/common/editor/lib/",//注意2：你的路径
        saveHTMLToTextarea: true,//注意3：这个配置，方便post提交表单
        // 图片上传
        imageUpload: true,
        imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
        imageUploadURL: "/upload/uploadFile"
    });
}

//将时间戳转化为时间
function fmt(timestamp) {
//13位时间戳转换
    var date = new Date(timestamp / 1);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + " " + h + ":" + minute + ":" + second;
}